package com.cheejee.goodscenter.util;

 import java.time.Instant;
import java.time.Period;
import java.util.Date;

import javax.annotation.Resource;

import com.cheejee.goodscenter.module.entity.Goods;
import com.cheejee.goodscenter.module.entity.SaleCount;
import com.cheejee.goodscenter.service.GoodsService;
import com.cheejee.goodscenter.service.SaleCountService;

import cn.hutool.cron.task.Task;

/**
 * 商品销量更新任务，根据商品SKU销售情况更新商品销量字段
 * @author CARRY
 * @Date 2020年10月27日上午1:33:06
 */
public class GoodsSaleTask implements Task{
	
	@Resource
	private GoodsService gs;
	@Resource
	private SaleCountService ss;

	private Long goodsId;
	
	public GoodsSaleTask(Long goodsId) {
		this.goodsId = goodsId;
	}


	@Override
	public void execute() {
		Instant now = Instant.now();
		Date begin = Date.from(now.minus(Period.ofDays(1)));
		Date end = Date.from(now);
		
		int count = ss.querySaleCountBetween(begin, end, goodsId, null, 0, 0).stream().mapToInt(SaleCount::getNum).sum();
		Goods goods = gs.queryGoodsById(goodsId);
		goods.setSale(goods.getSale() + count);
		
		gs.changeGoods(goods);
	}
	
}
